import config from './config.js'
class HTTP {
	request(params) {
		if (!params.method) params.method = 'GET';
		if (!params.data) params.data = '';
		let user = uni.getStorageSync('user');
		let notoken = [ 
			// 'ShopManageController/getGraticulesShopList', 
		'login/zfb' ];
		let notokenSwitch = false;
		notoken.forEach(ele => { if( params.url.indexOf(ele) > -1 ) { notokenSwitch = true; } });
		if(notokenSwitch){
			let url=config.url + params.url + '&t=' + new Date().getTime();
			url=url.replace(/\s/g,'');
			console.log(url);
			uni.request({
				url,
				method: params.method,
				data: params.data,
				dataType: 'json',
				success: function(res) {
					console.log(res,'res');
					if(res.statusCode==200&&res.data&&res.data.success) {
						params.success(res.data);
					}else if(res.data) {
						uni.showToast({ icon: 'none', title: res.data.reason });
						if(params.fail) params.fail(res.data);
					}
				},
				fail: function(error) {
					if(params.fail) params.fail(error);
				}
			});					
		} else {
			let url=config.url + params.url + '&t=' + new Date().getTime();
			url=url.replace(/\s/g,'');
			console.log(url);
			uni.request({
				url,
				method: params.method,
				data: params.data,
				header: { 'X-Access-Token': user ? user.token : '' },
				dataType: 'json',
				success: function(res) {
					console.log(res);
					if(res.statusCode==200&&res.data&&res.data.success) {
						params.success(res.data);
					}else if(res.data) {
						uni.showModal({ 
							title: '提示', content: res.data.reason, 
							showCancel: false,
							complete: () => {
								if(params.fail) params.fail(res.data);
							}
						});
					}else{
						if(params.fail) params.fail(res.data);
					}
				},
				fail: function(error) {
					if(params.fail) params.fail(error);
				}
			});			
		}
	}
}
export { HTTP }